package com.entrogy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.*;
import com.entrogy.dao.*;
import com.entrogy.service.StudentService;
import com.entrogy.timing.ChangePersonTimeThread;
import com.entrogy.utils.SendUtils;
import com.entrogy.utils.StrUtils;
import com.entrogy.utils.THDio;
import com.entrogy.utils.TimeUtils;
import com.entrogy.utils.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;

/**
 *  学生信息sevice接口实现类
 */
@Service
@Transactional
public class StudentServiceImpl implements StudentService {

	private static final Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);

	@Autowired
	private StudentMapper studentMapper;//学生信息dao接口
	@Autowired
	private ParentMapper parentMapper;//学生家长信息接口
	@Autowired
	private MachineMapper machineMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private SchoolMapper schoolMapper;
	@Autowired
	private DormMapper dormMapper;
	@Autowired
	private THDio thDio;
	@Autowired
	private MessageMapper messageMapper;

	/**
	 *  分页查询学生信息
	 * @param map
	 * @return  List
	 */
	@Override
	public List<Map<String,Object>> getTotalStudentList(Map<String,Object> map){
		return  studentMapper.getTotalStudentList(map);
	}

	/**
	 *   分页查询获取条数
	 * @param map
	 * @return  条数
	 */
	@Override
	public int getTotal(Map<String,Object> map) {
		List<Map<String,Object>> list = studentMapper.getTotal(map);
		int m = list.size();
		return m;
	}

	/**
	 *   新增学生信息
	 * @param studentEntity
	 * @return
	 */
	@Override
	public int insertStudent(StudentEntity studentEntity) {
		return studentMapper.insertStudent(studentEntity);
	}


	/**
	 * 修改学生信息
	 * @return 是否成功的返回值
	 */
	@Override
	public int updateStudent(StudentEntity studentEntity){
		// 如果ic卡不为空，那么需要更新实义德的ic卡信息
		StudentEntity studentFromDb = getStudentById(studentEntity.getId());
		SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(studentFromDb.getSchoolCode(), Constants.THDID_AI06);
		if (studentFromDb != null && StringUtils.isNoneBlank(studentEntity.getIcNumber()) && !studentEntity.getIcNumber().equals(studentFromDb.getIcNumber())) {
			Integer studentThdidId = studentFromDb.getStudentThdid();
			if (studentThdidId != 0){
				net.sf.json.JSONObject params = new net.sf.json.JSONObject();
				params.put("personnel_id", studentThdidId);
				params.put("ic_number", studentEntity.getIcNumber());
				logger.info("实义德修改学生IC信息开始：");
				net.sf.json.JSONObject res;
				res = thDio.THD_interface(schoolThdidUrl.getPathUrl(), "/personnel/change_info", params, false, schoolThdidUrl.getAccessToken());
				logger.info("实义德修改学生IC信息结果: " + res.toString());
			}
		}else if (studentFromDb == null){
			logger.info("录入学生IC卡信息时，学生不存在，ID为=>" + studentEntity.getId());
		}
		return studentMapper.updateStudent(studentEntity);
	}


	/**
	 *   修改父母id
	 * @param map
	 * @return
	 */
	@Override
	public int  updateStuent1(Map<String,Object> map){

		return studentMapper.updateStuent1(map);
	}

	@Override
	public StudentEntity getStudentById(int id) {
		return studentMapper.getStudentById(id);
	}

	@Override
	public List<StudentEntity> getStudentByGrade(String gradeId, Integer schoolCode) {
		return studentMapper.getStudentByGrade(gradeId, schoolCode);
	}

	//更新学生的控权时间 中午，下午，晚上 只有德育处的老师 有权限
	@Override
	public int updateStudentControl(String studentIDs, String allowTimes) {
		studentIDs = studentIDs.replaceAll("\\[", "");
		studentIDs = studentIDs.replaceAll("\\]", "").trim();
		allowTimes = allowTimes.replaceAll("\\[", "");
		allowTimes = allowTimes.replaceAll("\\]", "");
		allowTimes = allowTimes.replaceAll("\"", "");
		allowTimes = allowTimes.replaceAll("\"", "").trim();
		if(StrUtils.isNullOrEmpty(allowTimes)){
			return 2;
		}
		String[] strIDs = studentIDs.split(",");
		String[] allowTimesDB = allowTimes.split(",");
		for (int i = 0; i < allowTimesDB.length; i++) {
            StudentEntity student = getStudentById(Integer.parseInt(strIDs[i]));
            // 如果将住校生更改为走读生的话，那么需要将该学生宿舍id置位null
            if (!allowTimesDB[i].equals(student.getAllowTime()) && student.getAllowTime().equals("000")){
                student.setDormitory("");
                student.setFloorId(-1);
                updateStudent(student);
            }
            studentMapper.updateStudentControl(allowTimesDB[i], Integer.parseInt(strIDs[i]));
		}
		return 1;
	}

	@Override
	public int updateStudentSetUp(String userId, String studentIDs, String leaveTypes) {
		try {
			studentIDs = studentIDs.replaceAll("\\[", "").trim();
			studentIDs = studentIDs.replaceAll("\\]", "").trim();
			leaveTypes = leaveTypes.replaceAll("\\[", "").trim();
			leaveTypes = leaveTypes.replaceAll("\\]", "").trim();
			String[] stuDBs = studentIDs.split(",");
			String[] typeDBs = leaveTypes.split(",");
			for (int i = 0; i < stuDBs.length; i++) {
				int type = Integer.parseInt(typeDBs[i]);
				int stuID = Integer.parseInt(stuDBs[i]);
				studentMapper.updateStudentSetUp(type,stuID);
				logger.info("ID为" + stuID + "的学生离校type设置为了" + type + "");
			}
			return 1;
		} catch (Exception e) {
			logger.error("ID为" + userId + "的班主任或家长设置学生离校状态出错"+e.getMessage());
		} finally {
			if (userId.startsWith("1")) {// 说明班主任 设置了学生离校方式
				try {
					studentMapper.insertLeaveSchoolSet(userId);
				} catch (Exception e) {
					studentMapper.updateLeaveSchoolSet(userId);// 更新设置离校方式的时间
				}
			}
		}
		return 1;
	}

	@Override
	public List<Integer> findStuIdsByParentId(String uId) {
		return studentMapper.findStuIdsByParentId(uId);
	}

	@Override
	public Integer findClassIdByStuId(Integer stuId) {
		return studentMapper.findClassIdByStuId(stuId);
	}

	@Override
	public int setStudentGoHome(String uid, String stuId) {
		try {
			TimeUtils timeUtils = new TimeUtils();
			StudentEntity stu = studentMapper.getStudentById(Integer.parseInt(stuId));
			Date startTime = new Date();
			// 只加一个小时
			Date endTime = timeUtils.addDay(startTime, 0, 1, 0);
			MachineEntity machine = new MachineEntity();
			machine.setSchoolCode(stu.getSchoolCode()).setDeviceModel(Constants.THDID_AI06).setIsout(1);
			List<MachineEntity> machineList = machineMapper.listMachine(machine);
			Integer schoolCode = studentMapper.getStudentSchoolCode(Integer.valueOf(stuId));
			SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
			for (MachineEntity mBean : machineList) {
				String deviceId = mBean.getMachineId();
				if (stu.getStudentThdid() == 0){
					continue;
				}
				new ChangePersonTimeThread(deviceId, stu.getStudentThdid()+"", 1, 1, "全天ALL", 3,
						startTime.getTime() / 1000, endTime.getTime() / 1000,
						"接孩子", 0, schoolThdidUrl.getPathUrl(), schoolThdidUrl.getAccessToken()).start();
			}
			if (parentMapper.insertPickRecord(uid, stu.getId(), stu.getStudentName(), startTime, endTime)==1) {
				// 发送推送给班主任
				String userId = userMapper.getUserByClassID(stu.getCourseId(),stu.getSchoolCode());
				UserEntity userEntity = userMapper.getUserByUid(userId);
				String schoolName = schoolMapper.getSchoolName(schoolCode);
				String[] paramsWeiXin = { "", schoolName, "脸卡通", timeUtils.getCurrentDateTime(), stu.getStudentName() + "家长已设置出门权限" + timeUtils.getDateTime(startTime) + "-" + timeUtils.getDateTime(endTime), "" };
				PubCountEntity pubCountEntity = messageMapper.getPubCountOpenidByPhone(userEntity.getMobile());
				SendUtils.sendByWeixin(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId());
			} else {
				return 0;
			}
			return 1;
		} catch (Exception e) {
			logger.error(""+uid+"家长接送"+stuId+"设置报错");
			return 0;
		}
	}

	@Override
	public Integer findStudentBySchoolCodeAndClassId(Integer schoolCode, Integer classId, String studentName) {
		return studentMapper.getStudentBySchoolCodeAndClassId(schoolCode, classId, studentName);
	}

	@Override
	public List<JSONObject> listStudentAndInformationStatus(String uid, String showImage) {
		//查找出这个班主任所带班级的学生列表
		List<JSONObject> studentInformationList = studentMapper.listStudentSimpleInformation(uid);
		for (JSONObject student : studentInformationList) {
			Integer studentId = student.getInteger("id");
			//判断这名学生的家长是否有变更记录
			Integer hasChange = parentMapper.countStudentParentHasToAudit(studentId);
			if (hasChange > 0){
				student.put("hasChecked", true);
			}else {
				student.put("hasChecked", false);
			}
			// 查询该学生的家长有咩有登录
			Integer parentLoginCount = studentMapper.countParentLogin(studentId);
			//拼接图片回显地址
			String studentBase64 = showImage + File.separator + student.getString("studentBase64");
			student.remove("studentBase64");
			student.put("imageUrl", studentBase64);
			student.put("parentLoginStatus", parentLoginCount > 0 ? true : false);
		}
		return studentInformationList;
	}

	@Override
	public Integer getStudentIdByParentIdAndTeacherId(String uid, String teacherId) {
		return studentMapper.getStudentIdByParentIdAndTeacherId(uid, teacherId);
	}

	@Override
	public  List<Integer> getStudentId(String studentName, Integer classId, Integer schoolCode) {
		return studentMapper.getStudentId(studentName, classId, schoolCode);
	}

	@Override
	public List<JSONObject> listFloorStudent(Integer gradeId, Integer classId, Integer schoolCode) {
		return studentMapper.listFloorStudent(gradeId, classId, schoolCode);
	}

	@Override
	public List<StudentEntity> listSchoolAllStudent(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId, String studentName, String icNumber, String allowTime) {
		return studentMapper.listSchoolAllStudent(schoolCode, gradeId, classId, studentId, studentName, icNumber, allowTime);
	}

	@Override
	public boolean updateStudentThdid(Integer studentId, int thdId) {
		return studentMapper.updateStudentThdid(studentId, thdId);
	}

	@Override
	public Integer getStudentSchoolCode(Integer studentId) {
		return studentMapper.getStudentSchoolCode(studentId);
	}

	@Override
	public List<StudentEntity> listStudentByClassId(String classId, Integer schoolCode) {
		return studentMapper.listStudentByClassId(classId, schoolCode);
	}

	@Override
	public List<StudentEntity> batchInsertParentByPhone(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId) {
		List<StudentEntity> studentList = studentMapper.listSchoolAllStudent(schoolCode, gradeId, classId, studentId, null, null, null);
		List<StudentEntity> failStudentList = new ArrayList<>();
		logger.info("开始录入学生家长信息=》学生总计：" + studentList.size() + "人");
		int totalParent = 0;
		int failParent = 0;
		for (StudentEntity studentEntity : studentList) {
			boolean result = false;
			if (StringUtils.isNoneBlank(studentEntity.getParent1Id()) && studentEntity.getParent1Id().trim().length() == 11){
				logger.info("当前正在导入的学生"+ studentEntity.getStudentName() + "家长1电话号码是=>" + studentEntity.getParent1Id());
				totalParent++;
				result = insertParent(studentEntity, schoolCode, 1);
			}
			if (StringUtils.isNoneBlank(studentEntity.getParent2Id()) && studentEntity.getParent2Id().trim().length() == 11){
				logger.info("当前正在导入的学生"+ studentEntity.getStudentName() + "家长2电话号码是=>" + studentEntity.getParent2Id());
				if (!studentEntity.getParent2Id().equals(studentEntity.getParent1Id())){
					totalParent++;
					result = insertParent(studentEntity, schoolCode, 2);
				}
			}
			if (!result){
				failStudentList.add(studentEntity);
				failParent++;
			}
		}
		logger.info("学生家长信息录入完毕=》家长总计：" + totalParent + "人，" + "录入失败：" + failParent + "人");
		return failStudentList;
	}

	@Override
	public List<StudentEntity> allotStudentDorm(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId) {
		List<StudentEntity> failStudentList = new ArrayList<>();
		List<StudentEntity> studentList = studentMapper.listSchoolAllStudent(schoolCode, gradeId, classId, studentId, null, null, null);
		int successCount = 0;
		logger.info("开始进行学生宿舍分配=》学生总计：" + studentList.size() + "人");
		for (StudentEntity studentEntity : studentList) {
//			if (studentEntity.getDormitory() == null || studentEntity.getFloorId() == null){
//				continue;
//			}
//			Integer floorId = dormMapper.getFloorId(Integer.valueOf(studentEntity.getDormitory()), Integer.valueOf(studentEntity.getFloorId().toString().substring(0, 1)));
//			if (floorId != null){
//				int updateRow = studentMapper.updateStudentFloorId(floorId, studentEntity.getId());
//				if (updateRow > 0){
//					successCount++;
//				}
//			}
			// 推送通行权限到宿舍机器
			// 查询该楼层设备id
			if (studentEntity.getDormitory() != null && studentEntity.getFloorId() != null){
				List<String> deviceIds = dormMapper.listDormDevice(Integer.valueOf(studentEntity.getDormitory()));
				if (deviceIds.size() == 0){
					return studentList;
				}
				StringBuilder device_ids = new StringBuilder();
				for (String deviceId : deviceIds) {
					device_ids.append(deviceId).append(",");
				}
				String deviceIdStr = device_ids.substring(0, device_ids.length() - 1);
				net.sf.json.JSONObject params = new net.sf.json.JSONObject();
				//获取实义德后台地址
				SchoolThdidUrlEntity schoolThididUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
				params.put("device_ids", deviceIdStr);
				params.put("personnel_ids", studentEntity.getStudentThdid());
				params.put("type", 1);
				params.put("cycle_id", 1);
				params.put("pass_number", 10000);
				params.put("pass_start_time", 111111111);
				params.put("pass_end_time", 99999999999L);
				logger.info("宿舍添加学生开始：" + studentEntity.getStudentName() + "分配到设备：" + deviceIdStr);
				net.sf.json.JSONObject res;
				THDio thdio = new THDio();
				res = thdio.THD_interface(schoolThididUrl.getPathUrl(), "/competence/change_personnel_pass", params, false, schoolThididUrl.getAccessToken());
				logger.info("宿舍添加学生结果: " + res.toString());
				if (res.getInt("code") != 0) {
					failStudentList.add(studentEntity);
					continue;
				}
			}
		}
		logger.info("学生宿舍分配成功" + successCount + "人");
		return failStudentList;
	}

	@Override
	public List<StudentEntity> initStudentData(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId) {
		logger.info("开始初始化学生基本信息：");
		int updateStudentBasicDataRow = studentMapper.updateStudentBasicData(schoolCode, gradeId, classId, studentId);
		int updateStudentSexDataRow = studentMapper.updateStudentSexData(schoolCode, gradeId, classId, studentId);
		int updateStudentLeaveTypeDataRow = studentMapper.updateStudentLeaveTypeData(schoolCode, gradeId, classId, studentId);
		logger.info("初始化学生基本信息结果=》基本信息更新条数：" + updateStudentBasicDataRow + "条，" + "性别信息更新条数：" + updateStudentSexDataRow + "条，"
		+ "离校信息更新条数：" + updateStudentLeaveTypeDataRow + "条");
		return null;
	}

	@Override
	public boolean deleteStudent(Integer schoolCode, Integer gradeId, Integer classId, Integer studentId) {
		return studentMapper.deleteStudent(schoolCode, gradeId, classId, studentId) > 0;
	}

	@Override
	public List<StudentEntity> listSchoolStudent() {
		return studentMapper.listSchoolStudent();
	}

	@Override
	public Integer getStudentCycleId(int id, String cycleTableName) {
		return studentMapper.getStudentCycleId(id, cycleTableName);
	}

	@Override
	public boolean updateStudentInfo(Integer studentId, String studentPhotoUrl) {
		return studentMapper.updateStudentInfo(studentId, studentPhotoUrl) == 1;
	}

	@Override
	public boolean studentIsPay(int studentId) {
		return studentMapper.getStudentPayStatus(studentId) != null;
	}

	@Override
	public List<StudentIcEntity> listStudentForIcManager(Integer schoolCode, Integer isBind, Integer gradeId, Integer classId, String studentName) {
		return studentMapper.listStudentForIcManager(schoolCode, isBind, gradeId, classId, studentName);
	}

	@Override
	public int countStudentForIcManager(Integer schoolCode, Integer isBind, Integer gradeId, Integer classId, String studentName) {
		return studentMapper.countStudentForIcManager(schoolCode, isBind, gradeId, classId, studentName);
	}

	@Override
	public List<StudentBasicInfoEntity> listStudentForBus(Integer busLineId, String studentName, Integer schoolCode) {
		return studentMapper.listStudentForBus(busLineId, studentName, schoolCode);
	}

	@Override
	public Integer countStudentForBus(Integer busLineId, String studentName, Integer schoolCode) {
		return studentMapper.countStudentForBus(busLineId, studentName, schoolCode);
	}

	private boolean insertParent(StudentEntity studentEntity, Integer schoolCode, Integer parentType){
//		ParentVisitorEntity temp = parentMapper.getParentByPhone(parentType == 1 ? studentEntity.getParent1Id() : studentEntity.getParent2Id());
//		if (temp != null){
//			return false;
//		}
//		ParentVisitorEntity temp1 = parentType == 1 ? parentMapper.getparentById(studentEntity.getParent1Id()) : parentMapper.getparentById(studentEntity.getParent2Id());
//		if (temp1 != null){
//			return false;
//		}
//		ParentVisitorEntity parentVisitorEntity = new ParentVisitorEntity();
//		parentVisitorEntity.setParentVisitorName(parentType == 1 ? studentEntity.getStudentName() + "家长1" : studentEntity.getStudentName() + "家长2");
//		parentVisitorEntity.setParentVisitorPhone(parentType == 1 ? studentEntity.getParent1Id() : studentEntity.getParent2Id());
//		parentVisitorEntity.setParentVisitorSchoolCode(schoolCode);
//		parentVisitorEntity.setParentVisitorStudentId(studentEntity.getId());
//		String parent_visitor_id = ("3" + System.currentTimeMillis());
//		parentVisitorEntity.setParentVisitorType(parentType == 1 ? 1 : 2);
//		parentVisitorEntity.setParentVisitorId(parent_visitor_id);
//		int insertRow = parentMapper.insertParent(parentVisitorEntity);
//		Map<String, Object> map = new HashMap<>();
//		map.put("id", studentEntity.getId());
//		map.put("parent_id", parent_visitor_id);
//		if (parentType == 1) {
//			map.put("type", 1);
//		} else {
//			map.put("type", 2);
//		}
//		int updateRow = studentMapper.updateStuent1(map);
		ParentVisitorEntity parentVisitorEntityFromDB = parentMapper.getParentByPhone(parentType == 1 ? studentEntity.getParent1Id().trim() : studentEntity.getParent2Id().trim());
		ParentVisitorEntity parentVisitorEntity = new ParentVisitorEntity();
		int insertRow = 0;
		if (parentVisitorEntityFromDB == null){
			parentVisitorEntity.setParentVisitorName(parentType == 1 ? studentEntity.getStudentName() + "家长1" : studentEntity.getStudentName() + "家长2");
			parentVisitorEntity.setParentVisitorPhone(parentType == 1 ? studentEntity.getParent1Id().trim() : studentEntity.getParent2Id().trim());
			parentVisitorEntity.setParentVisitorSchoolCode(schoolCode);
			String parent_visitor_id = ("3" + System.currentTimeMillis());
			parentVisitorEntity.setParentVisitorType(parentType == 1 ? 1 : 2);
			parentVisitorEntity.setParentVisitorId(parent_visitor_id);
			insertRow = parentMapper.insertParent(parentVisitorEntity);
		}
		Map<String, Object> map = new HashMap<>();
		map.put("id", studentEntity.getId());
		map.put("parent_id", parentVisitorEntityFromDB == null ? parentVisitorEntity.getParentVisitorId() : parentVisitorEntityFromDB.getParentVisitorId());
		if (parentType == 1) {
			map.put("type", 1);
		} else {
			map.put("type", 2);
		}
		int updateRow = studentMapper.updateStuent1(map);
		return insertRow == 1 && updateRow == 1;
	}

	@Override
	public boolean updateStudentAllThdid(Integer studentId, Map<String, Integer> thdidInfo) {
		Integer studentAi06ThdidId = thdidInfo.get("studentThdidAi06Id");
		Integer studentAi16ThdidId = thdidInfo.get("studentThdidAi16Id");
		if(studentAi06ThdidId == null && studentAi16ThdidId == null){
			return false;
		}
		StudentEntity student = new StudentEntity();
		student.setId(studentId);
		if (studentAi06ThdidId != null)
			student.setStudentThdid(studentAi06ThdidId);
		student.setStudentThdidAi16Id(studentAi16ThdidId);
		studentMapper.updateStudent(student);
		return true;
	}

	@Override
	public int countStudent(Integer schoolCode, Integer gradeId, Integer courseId, String studentName) {
		return studentMapper.countStudent(schoolCode, gradeId, courseId, studentName);
	}


}
